package com.sx.pipeline.ui.task.participate.process

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.BitmapFactory
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lxj.xpopup.XPopup
import com.permissionx.guolindev.PermissionX
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IdentityType
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.ActProcessingTasksBinding
import com.sx.pipeline.ui.task.participate.ParticipateTaskVM
import com.sx.pipeline.utils.AndroidUtil
import com.sx.pipeline.utils.CompressHelper
import com.sx.pipeline.utils.GlideEngine
import com.sx.pipeline.utils.PermissionHelper


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 我的发布-任务详情-处理任务
 */
@Route(path = RoutePath.Mine.TASK_PROCESS)
class ProcessTaskActivity : CYDataBindingBaseActivity<ActProcessingTasksBinding, ParticipateTaskVM>
    (R.layout.act_processing_tasks), View.OnClickListener {

    @JvmField
    @Autowired(name = IntentKey.ID)
    var taskId: Int? = 0

    @JvmField
    @Autowired(name = IntentKey.STATUS)
    var hasGroup: String? = ""

    override fun initData() {
        super.initData()
        Logs.d("re是否加入群聊" + hasGroup)
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }


        //获取当前登录单位信息
        mViewModel.getUserUnit()

        //判断当前身份 运营单位/施工单位
        when (mViewModel.mModel.getIdentityType()) {
            IdentityType.OPERATING_UNIT.code -> {
                //运营单位
                mBinding.tvUnitType.text = getString(R.string.txt_participate_in_disclosure_unit)
                mBinding.tvContactType.text = getString(R.string.txt_operator)
                mBinding.tabDesc.visibility = View.VISIBLE
                mBinding.tabImages.visibility = View.VISIBLE
                mBinding.tabMilieudesc.visibility = View.GONE
                mBinding.tabNeedNeed.visibility = View.GONE
            }
            IdentityType.BUILD_UNIT.code -> {
                //施工单位
                mBinding.tvUnitType.text =
                    getString(R.string.txt_participate_in_construction_disclosure_units)
                mBinding.tvContactType.text = getString(R.string.txt_construction_workers)
                mBinding.tabDesc.visibility = View.GONE
                mBinding.tabImages.visibility = View.GONE
                mBinding.tabMilieudesc.visibility = View.VISIBLE
                mBinding.tabNeedNeed.visibility = View.VISIBLE
            }
        }

        // 上传图片
        mBinding.imageUploadView.initAdapter(3, 3)
        mBinding.imageUploadView.setImageUploadListener {
            PermissionHelper.requestTip(this,"上次图片需要授权相机和读写权限",object :
                PermissionUtils.SimpleCallback{
                override fun onGranted() {
                    PictureSelector.create(this@ProcessTaskActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(3 - mBinding.imageUploadView.imagePath.size)
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {
                            override fun onResult(result: ArrayList<LocalMedia?>?) {
                                //循环上传图片
                                for (i in 0 until result?.size!!) {
                                    Log.d("okhttp", "" + result[i]?.realPath)
                                    //压缩图片
                                    val inputBitmap =
                                        BitmapFactory.decodeFile(result[i]?.realPath)
                                    val compressFile = CompressHelper.compressQuality(
                                        this@ProcessTaskActivity,
                                        inputBitmap
                                    )
                                    mViewModel.uploadImage(compressFile)
                                }
                            }

                            override fun onCancel() {}
                        })
                }

                override fun onDenied() {
                    ToastUtils.showShort("请授权后再继续操作")
                }
            },Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)

//            PermissionX.init(this)
//                .permissions(
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.CAMERA
//                )
//                .onExplainRequestReason { scope, deniedList ->
//                    scope.showRequestReasonDialog(
//                        deniedList,
//                        "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                        "确认",
//                        "取消"
//                    )
//                }
//                .onForwardToSettings { scope, deniedList ->
//                    scope.showForwardToSettingsDialog(
//                        deniedList,
//                        "您需要手动在“设置”中允许必要的权限",
//                        "确定",
//                        "取消"
//                    )
//                }
//                .request { allGranted, _, deniedList ->
//                    if (allGranted) {
//                        PictureSelector.create(this)
//                            .openGallery(SelectMimeType.ofImage())
//                            .setImageEngine(GlideEngine.createGlideEngine())
//                            .setMaxSelectNum(3 - mBinding.imageUploadView.imagePath.size)
//                            .forResult(object : OnResultCallbackListener<LocalMedia?> {
//                                override fun onResult(result: ArrayList<LocalMedia?>?) {
//                                    //循环上传图片
//                                    for (i in 0 until result?.size!!) {
//                                        Log.d("okhttp", "" + result[i]?.realPath)
//                                        //压缩图片
//                                        val inputBitmap =
//                                            BitmapFactory.decodeFile(result[i]?.realPath)
//                                        val compressFile = CompressHelper.compressQuality(
//                                            this@ProcessTaskActivity,
//                                            inputBitmap
//                                        )
//                                        mViewModel.uploadImage(compressFile)
//                                    }
//                                }
//
//                                override fun onCancel() {}
//                            })
//                    } else {
//                        ToastUtils.showShort(getString(R.string.txt_these_permissions_are_denied))
//                    }
//                }

        }

    }

    override fun initViewObservable() {
        super.initViewObservable()
        //当前登录单位信息
        observe(mViewModel.userUnitEvent) {
            mBinding.tvCurrentUnit.text = it?.name
        }

        //图片上传结果
        observe(mViewModel.uploadDataEvent) {
            mBinding.imageUploadView.addImage(it)
        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            //提交处理任务
            R.id.tv_submit -> {

                //判断当前身份  运营单位处理任务
                when (mViewModel.mModel.getIdentityType()) {
                    IdentityType.OPERATING_UNIT.code -> {
                        if (TextUtils.isEmpty(mBinding.etContact.text.toString())) {
                            ToastUtils.showShort("请填写运营人员名称")
                            return
                        }
                        if (TextUtils.isEmpty(mBinding.etDesc.text.toString())) {
                            ToastUtils.showShort("请填写交底内容描述")
                            return
                        }
                        if (mBinding.imageUploadView.imagePath.size == 0) {
                            ToastUtils.showShort("请上传图片")
                            return
                        }

                        //false无群，不加入
                        if (hasGroup != "true") {
                            var contact = mBinding.etContact.text.toString()
                            var desc = mBinding.etDesc.text.toString()
                            taskId?.let {
                                AndroidUtil.listToString(mBinding.imageUploadView.imagePath)
                                    ?.let { it1 ->
                                        mViewModel.dealWithTask(
                                            1,
                                            it, contact, desc, it1, "", "", "false"
                                        )
                                    }
                            }

                        } else {
                            //true 有群聊并且可以加入群
                            XPopup.Builder(
                                this
                            )
                                .isDestroyOnDismiss(true) //                        .dismissOnBackPressed(false)
                                .dismissOnTouchOutside(false)
                                .asConfirm(
                                    getString(R.string.hint), getString(R.string.q_task_join_group),
                                    getString(R.string.cancel), getString(R.string.confirm),
                                    {
                                        var contact = mBinding.etContact.text.toString()
                                        var desc = mBinding.etDesc.text.toString()
                                        taskId?.let {
                                            AndroidUtil.listToString(mBinding.imageUploadView.imagePath)
                                                ?.let { it1 ->
                                                    mViewModel.dealWithTask(
                                                        1,
                                                        it, contact, desc, it1, "", "", "true"
                                                    )
                                                }
                                        }
                                    },
                                    {
                                        var contact = mBinding.etContact.text.toString()
                                        var desc = mBinding.etDesc.text.toString()
                                        taskId?.let {
                                            AndroidUtil.listToString(mBinding.imageUploadView.imagePath)
                                                ?.let { it1 ->
                                                    mViewModel.dealWithTask(
                                                        1,
                                                        it, contact, desc, it1, "", "", "false"
                                                    )
                                                }
                                        }
                                    }, false
                                ).show()
                        }
                    }
                    //施工单位处理任务
                    IdentityType.BUILD_UNIT.code -> {
                        if (TextUtils.isEmpty(mBinding.etContact.text.toString())) {
                            ToastUtils.showShort("请填写施工人员名称")
                            return
                        }
                        if (TextUtils.isEmpty(mBinding.etConstructionEnvironment.text.toString())) {
                            ToastUtils.showShort("请填写配套服务需求")
                            return
                        }
                        if (TextUtils.isEmpty(mBinding.etServiceNeed.text.toString())) {
                            ToastUtils.showShort("请填写配套服务需求")
                            return
                        }

                        //false无群，不加入
                        if (hasGroup != "true") {
                            var contact = mBinding.etContact.text.toString()
                            taskId?.let {
                                mViewModel.dealWithTask(
                                    0,
                                    it,
                                    contact,
                                    "",
                                    "",
                                    mBinding.etConstructionEnvironment.text.toString(),
                                    mBinding.etServiceNeed.text.toString(),
                                    "false"
                                )
                            }
                        } else {
                            //true 有群聊并且可以加入群
                            XPopup.Builder(
                                this
                            )
                                .isDestroyOnDismiss(true) //                        .dismissOnBackPressed(false)
                                .dismissOnTouchOutside(false)
                                .asConfirm(
                                    getString(R.string.hint), getString(R.string.q_task_join_group),
                                    getString(R.string.cancel), getString(R.string.confirm),
                                    {
                                        var contact = mBinding.etContact.text.toString()
                                        taskId?.let {
                                            mViewModel.dealWithTask(
                                                0,
                                                it,
                                                contact,
                                                "",
                                                "",
                                                mBinding.etConstructionEnvironment.text.toString(),
                                                mBinding.etServiceNeed.text.toString(),
                                                "true"
                                            )
                                        }
                                    },
                                    {
                                        var contact = mBinding.etContact.text.toString()
                                        taskId?.let {
                                            mViewModel.dealWithTask(
                                                0,
                                                it,
                                                contact,
                                                "",
                                                "",
                                                mBinding.etConstructionEnvironment.text.toString(),
                                                mBinding.etServiceNeed.text.toString(),
                                                "false"
                                            )
                                        }
                                    }, false
                                ).show()
                        }
                    }
                }
            }
        }
    }

}